<template>
  <div id="map">
    <button id="btn1"> 点击绘制 </button>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import * as Cesium from "cesium"
import draw from "./draw"
import drawEntity from "./drawEntity"

onMounted(() => {
  const tk = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhMjEwZDE1NS0zM2YwLTRhNTgtYjMyZC1hMTJhYzg5Y2Q1NDMiLCJpZCI6MTk3NzY0LCJpYXQiOjE3MDg4ODQxNjJ9.oD0CyRJ91NpOFmkWr4D6ICms0doNkl18quIaTrlfsww"
  Cesium.Ion.defaultAccessToken = tk

  // 把默认home坐标从美国改到中国
  Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(80, 22, 130, 55)

  const viewer = new Cesium.Viewer("map", {
    scene3DOnly: false,
    selectionIndicator: false,
    infoBox: false,
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    projectionPicker: false,
    baseLayerPicker: false,
    navigationHelpButton: false,
    animation: false,
    timeline: false,
    fullscreenButton: false,
    vrButton: false,
    skyBox: false,
    shouldAnimate: false,
    targetFrameRate: 60,
  });

  // 指向日照
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(119.4, 35.5, 10000.0),
    orientation: {
      heading: Cesium.Math.toRadians(0), // 水平偏角，默认正北 0
      pitch: Cesium.Math.toRadians(-90), // 俯视角，默认-90，垂直向下
      roll: 0, // 旋转角
    },
  });
  // 移除默认地图
  viewer.imageryLayers.removeAll()

  viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
      url: Cesium.IonResource.fromAssetId(1)
  });

  viewer.imageryLayers.addImageryProvider(
    new Cesium.UrlTemplateImageryProvider({
      url: "https://onepage.city.shuzirizhao.cn/source/raster/{z}/{x}/{y}.webp",
      maximumLevel: 18
    })
  );

  /**
   * 以下代码块加入三维模型
   */

  // const url = ""
  // const tileset = new Cesium.Cesium3DTileset({
  //   url: url,
  //   maximumScreenSpaceError: 6
  // })
  // viewer.scene.primitives.add(tileset)
  // viewer.zoomTo(tileset)

  // 深度测试
  viewer.scene.globe.depthTestAgainstTerrain = true
  // 关闭地表大气
  viewer.scene.globe.showGroundAtmosphere = false
  // 移除Cesium版权徽标
  viewer.cesiumWidget.creditContainer.remove()

  // 点击按钮 开始绘制
  document.getElementById("btn1")?.addEventListener("click", () => {

    let coordArray: Array<Array<number>> = []
    let tempArray: Array<Array<number>> = []
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    let absoluteHeight: number

    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    handler.removeInputAction(Cesium.ScreenSpaceEventType.MIDDLE_CLICK)

    // LEFT_CLICK
    handler.setInputAction((e: any) => {
      // 删除entity
      viewer.entities.getById("temp")

      let cartesian3 = viewer.scene.pickPosition(e.position);
      let cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
      const coord_c = [Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), cartographic.height]
      if (tempArray.length === coordArray.length) {
        coordArray.push(coord_c)
      } else {
        coordArray.push(coord_c)
        tempArray.pop()
        tempArray.push(coord_c)
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    // Mouse Move
    handler.setInputAction((e: any) => {
      let cartesian3 = viewer.scene.pickPosition(e.endPosition);
      let cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
      const coord_m = [Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), cartographic.height]
      if (tempArray.length === coordArray.length) {
        tempArray.push(coord_m)
      } else {
        tempArray.pop()
        tempArray.push(coord_m)
      }
      draw(viewer, tempArray)
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    handler.setInputAction(() => {
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
      handler.setInputAction((e: any) => {
        let cartesian3 = viewer.scene.pickPosition(e.endPosition);
        let cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
        absoluteHeight = cartographic.height + 1;
        drawEntity(viewer, coordArray, absoluteHeight)
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

    handler.setInputAction(() => {
      let geojson = {
        "type": "Feature",
        "properties": {
          "height": "",
          "build_name": ""
        },
        "geometry": {
          "type": "Polygon",
          "coordinates": [
            [
            ]
          ]
        }
      }

      coordArray.forEach((coord: Array<number>) => {
        // @ts-ignore
        geojson.geometry.coordinates[0].push([coord[0], coord[1]])
      });
      // @ts-ignore
      geojson.geometry.coordinates[0].push([coordArray[0][0], coordArray[0][1]])
      geojson.properties.height = absoluteHeight.toString()

      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MIDDLE_CLICK)
    }, Cesium.ScreenSpaceEventType.MIDDLE_CLICK)
  })

  // --------------------------------------------------------------------------------------------
  // 点击标点

})
</script>

<style scoped>
#map {
  height: 100%;
  width: 100%;
}

#btn1 {
  position: absolute;
  left: 50px;
  top: 50px;
  z-index: 999;
}

#btn2 {
  position: absolute;
  left: 50px;
  top: 100px;
  z-index: 999;
}
</style>